package com.tjc.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.tjc.apiclientsdk.model.User;
import com.tjc.apiclientsdk.util.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ApiClient
 * @Author tjc
 **/
public class ApiClient {
    // 网关的默认地址
    private static final String GATEWAY_HOST = "http://127.0.0.1:6636";
    // private static final String GATEWAY_HOST = "http://127.0.0.1:7530";


    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * @param body 用户自己掺入的参数
     * @return 请求头的内容
     */
    public Map<String, String> getHeaderMap(String body) {
        Map<String, String> headerMap = new HashMap<String, String>();

        // 放入ak，方便后面去数据库中查询sk
        headerMap.put("accessKey", accessKey);
        // 放入随机数，防止重放
        headerMap.put("nonce", RandomUtil.randomNumbers(4));
        // 放入时间戳防止重放
        headerMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
        // 放入api签名，和服务器规定好的加密方式进行解密
        headerMap.put("sign", SignUtils.getSign(secretKey, body));
        // 放入body参数
        headerMap.put("body", body);

        return headerMap;
    }

    /**
     * 这个方法就是这个sdk内置的请求方法，能够远程调用接口返回结果
     *
     * @param user 传入的请求参数
     * @return
     */
    public String getNameByRestful(User user) {
        String json = JSONUtil.toJsonStr(user);

        HttpResponse httpResponse = HttpRequest
                .post(GATEWAY_HOST + "/api/name/user")
                // .post(GATEWAY_HOST + "/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);

        return result;
    }

}
